import React, { FC, useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { SwipeAction, SearchBar } from 'antd-mobile-v2';
import styles from './index.module.less';
import { Props, State } from '../../../type';
import { GetProvideItem } from '@/services/laber-declare';
import AntdRefreshList from '@/components/antd-refresh-list';
import EmptyRefresh from '@/components/empty/empty-refresh';
import classnames from 'classnames';
import { DETAIL_MODE } from '@/plugins/form/form-components/laber-detail/constants';
import { Button } from "antd-mobile-v2";

let debounceTimer = null; // 搜索防抖计时器

export interface DetailModal extends Props {
  onLaberEdit?: (index) => void;
  addModal?: () => void;
  form: any;
  value: any[];
  onCloseModal: () => void;
  detailMode?: State['detailMode'];
  mattersList?: [],
  onMatterDelete?: (index: number, id: any) => {}
}

export interface GetDataListParams {
  id?: string;
  list: any[];
  pageNum?: number;
  source?: DETAIL_MODE.EXPORT | DETAIL_MODE.NO_EXPORT; // 明细列表展示模式（1-导入 2-人工录入）
  keyWord?: string;
}

const detailModal: FC<DetailModal> = (props) => {
  const [values, setValues] = useState([] as any[]);
  const [showValues, setShowValues] = useState([] as any[]);
  const [keyword, setKeyword] = useState<string>();
  const [showDom, setshowDom] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  let { mattersList } = props;

  useEffect(() => {
    handleRefresh();
  }, [props.value]);

  useEffect(() => {
    if (keyword === undefined) return;
    searchListByKeyword(keyword);
  }, [keyword]);

  const getSearchName = (name) => {
    const locationStr = location.hash?.split('?')?.[1];
    const arr = locationStr?.split('&');
    const obj: any = {};
    for (let i = 0; i < arr?.length; i++) {
      const aItem = arr[i]?.split('=');
      obj[aItem[0]] = decodeURIComponent(aItem[1]);
    }
    return obj?.[name] || '';
  };

  const onOpen = (index) => {
    console.log('global open', index);
  };

  const onClose = () => {
    console.log('global close');
  };

  const rightBtns = (index: number, id: any) => {
    return [
      {
        text: '删除',
        onPress: () => onMatterDelete(index, id),
        style: { backgroundColor: '#FF3A30', color: 'white', fontSize: '18px', padding: '7px' }
      }
    ];
  };

  // 删除
  const onMatterDelete = (index: number, id: any) => {
    props.onMatterDelete && props.onMatterDelete(index, id);
  };

  const searchChange = (value: string) => {
    setKeyword(value);
  };

  const searchListByKeyword = async (value: string) => {
    if (debounceTimer) {
      clearTimeout(debounceTimer);
    }
    debounceTimer = setTimeout(async () => {
      setRefreshing(true);
      await getDataList({ id: '', list: [], pageNum: 1, keyWord: value });
      setRefreshing(false);
      clearTimeout(debounceTimer);
    }, 0.8 * 1000);
  };

  const getDataList = async (params: GetDataListParams) => {
    setRefreshing(true);
    const reportId = getSearchName('applyId');
    let res: any = { data: {} };
    if (reportId && props.detailMode === DETAIL_MODE.EXPORT) {
      const data = {
        reportId: reportId,
        source: props.detailMode
      };
      res = await GetProvideItem(data);
    } else {
      res = {
        data: props.value || []
      };
    }
    setshowDom(true);
    const list = filterKeyWord(params.keyWord, res.data);
    console.log(list);
    setValues(list);
    setShowValues(list);
  };

  const filterKeyWord = (keyWord: string, list: any[]): any[] => {
    const reg = new RegExp(keyWord);
    console.log('list', list);
    return list.filter((item: any) => {
      if (props.detailMode === DETAIL_MODE.EXPORT) {
        return reg.test(item.studentCode) || reg.test(item.studentName);
      } else {
        const studentCode = item.studentCode?.value || item.studentCode;
        const studentName = item.studentCode?.studentName || item.studentName;
        return reg.test(studentCode) || reg.test(studentName);
      }
    });
  };

  const handleRefresh = async () => {
    setRefreshing(true);
    await getDataList({ id: '', list: [], pageNum: 1, keyWord: keyword });
    setRefreshing(false);
  };

  const goDetail = props?.goDetail;

  return (
    <div className={styles.detailModalWrapper}>
      {/* <div className={styles.searchWrap}>
        <SearchBar
          placeholder="开户姓名/证件号"
          value={keyword}
          onChange={searchChange}
        />
      </div> */}
      {
        mattersList?.length > 0 ?
          <div className={classnames(styles.laberDetailWrapper, props.renderMode === 'detail' || props.detailMode === 1 ? styles.noFooter : '')}>
            <AntdRefreshList
              dataSource={mattersList}
              refreshing={false}
              loadingMore={false}
              showFooterText={false}
              enableRefresh={false}
              // loadingMore={loadingMore}
              renderRow={(item, sectionID, index) => (
                <div key={item.id + index}>
                  <SwipeAction
                    style={{ backgroundColor: 'gray' }}
                    right={rightBtns(index, item.id)}
                    onOpen={() => onOpen(index)}
                    onClose={() => onClose()}
                    disabled={props.renderMode == 'detail' || props.detailMode === DETAIL_MODE.EXPORT}
                  >
                    <div className={styles.laberDetailContent}>
                      <div className={styles.title}>
                        <div className={styles.titleLeft} onClick={() => goDetail && goDetail(item)}>{item.matterName}</div>
                      </div>
                      <div className={styles.content}>
                        <div className={styles.titleRight}>{`[${item.orgName}][${item.documentCode}]`}</div>
                      </div>
                    </div>
                  </SwipeAction>
                </div>
              )}
            // onRefresh={handleRefresh}
            // onEndReached={handleLoadMore}
            />
          </div>
          : (
            <EmptyRefresh
              refreshing={refreshing}
            // onRefresh={handleRefresh}
            />
          )
      }
      <Button type="primary" className={styles.confirmBtn} onClick={() => props.onCloseModal && props.onCloseModal()}>
        关闭
      </Button>
    </div>
  );
};

export default connect()(detailModal);
